package com.qf.filter;


import com.qf.pojo.AdminPojo;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    static String STATIC_RES = ".eot.svg.ttf.woff.jpg.jpeg.png.gif.css.js.html.jsp";
    static String NOAUTH_PATH = "/jump/adminLogin/welcome";

    //使用过滤器一定要留下一条正常访问的路径
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //得到当前的请求地址;
        String requestpath = request.getServletPath();
        //用户访问静态资源,jsp页面,不需要过滤;
        if(requestpath.lastIndexOf(".") > 0){
            String hz = requestpath.substring(requestpath.lastIndexOf("."));

            if(STATIC_RES.indexOf(hz) != -1){
                filterChain.doFilter(request, response);
                return;
            }
        }

        //没有设置不需要权限就能访问的地址
        if(NOAUTH_PATH.indexOf(requestpath) != -1){
            filterChain.doFilter(request, response);
            return;
        }

        //说明该用户没有进行登录
        AdminPojo admin = (AdminPojo) request.getSession().getAttribute("adminPojo");
        if(null == admin){
            response.sendRedirect("jump");
            return;
        }

        //判断当前用户是否有权限访问这个地址
        String strAuths = (String) request.getSession().getAttribute("strAuths");

//        if(strAuths.contains(requestpath)) //说明找到了这个请求地址

        if(strAuths.indexOf(requestpath) != -1){ //说明找到了这个请求地址
            filterChain.doFilter(request,response);
        }else{
            response.sendRedirect("noauth.jsp");
        }
    }


    @Override
    public void destroy() {

    }
}
